package fun.boomcat.luckyhe.mirai.plugin.botcontrol.util;

import fun.boomcat.luckyhe.mirai.plugin.botcontrol.pojo.Config;
import net.mamoe.mirai.console.command.CommandSender;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.*;

/**
 * @author Lucky_He
 * @date 2021年8月27日 9:01
 * @description EventOperation
 */
public class EventOperation {
    public static void eventOperation(CommandSender commandSender, Object[] args) {
        List<Integer> ids = new ArrayList<>();
        for (Object arg : args) {
            try {
                ids.add(Integer.parseInt(arg.toString()));
            } catch (Exception e) {
                commandSender.sendMessage("错误：" + e.toString());
                return;
            }
        }

        List<String> keys;
        try {
            keys = getEventNameById(ids);
        } catch (Exception e) {
            commandSender.sendMessage("错误：" +  e.toString());
            return;
        }

        String res;
        try {
            res = changeState(keys);
        } catch (Exception e) {
            commandSender.sendMessage("错误：" + e.toString());
            return;
        }

        commandSender.sendMessage(res);
    }

    private static List<String> getEventNameById(List<Integer> ids) throws Exception {
        Config config = ConfigUtil.getConfig();
        Set<Map.Entry<String, Boolean>> entries = config.getEvents().entrySet();
        List<String> res = new ArrayList<>();

        int i = 0;
        for (Map.Entry<String, Boolean> entry : entries) {
            if (ids.contains(i)) {
                res.add(entry.getKey());
                ids.remove((Integer) i);
            }
            i++;
        }

        if (ids.size() != 0) {
            StringBuilder sb = new StringBuilder();

            sb.append("这些编号对应的事件不存在：");
            for (int id : ids) {
                sb.append(id).append(" ");
            }

            throw new Exception(sb.toString().trim());
        }

        return res;
    }

    private static String changeState(List<String> keys) throws IOException {
        StringBuilder sb = new StringBuilder();
        sb.append("已修改事件通知：\n");

        Config config = ConfigUtil.getConfig();
        for (String key : keys) {
            Boolean state = config.getEvents().get(key);
            sb.append(key).append("：").append(state).append(" -> ");

            if (state) {
                config.getEvents().put(key, false);
            } else {
                config.getEvents().put(key, true);
            }

            sb.append(config.getEvents().get(key)).append("\n");
        }

        ConfigUtil.writeConfig();

        return sb.toString();
    }
}
